package org.dgm.nw.core.viewControl;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dgm.nw.common.MenuActionFactory;
import org.dgm.nw.core.control.SpringBeanFactory;
import org.dgm.nw.core.viewControl.model.ActionInstance;
import org.dgm.nw.core.viewControl.model.ReqData;

/**
 * 核心业务转发器
 * 
 * @author wangwz
 * @date Aug 31, 2010
 * @version RCS: $Id: ActionServlet.java 583040 2011-10-22 02:47:49Z lianglg2 $
 */
public class ActionServlet extends HttpServlet {

	/**
	 * serialVersionUID:TODO（用一句话描述这个变量表示什么）
	 */
	private static final long serialVersionUID = 1L;

	Logger log = logger.getLogger(this.getClass());

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ActionServlet.class);

	// private static final Map<String, String> CLASS_PREFIX_MAP;
	// static {
	// // 初始化三类Action的相对包路径
	// // key为web.xml配置的servlet路径
	// CLASS_PREFIX_MAP = new HashMap<String, String>();
	// CLASS_PREFIX_MAP.put("public", "com.asiainfo.commons.framework.action");
	// for (String key :
	// Arrays.asList(SysConfigHelper.getParam(SysConfigKeyContainer.LOCALTION_SRC,
	// SysConfigHelper.getParam(SysConfigKeyContainer.LOCALTION,
	// "")).split(","))) {
	// if ("".equals(key) || key == null) {
	// continue;
	// }
	// CLASS_PREFIX_MAP.put(key, "com.asiainfo.openboss." + key);
	// }
	// }

	/**
	 * 根据key转换路径
	 * 
	 * @param key
	 * @return
	 */
	private static String getClassPrefix(String key) {
		if ("public".equals(key)) {
			return "com.asiainfo.commons.framework.action";
		}

		return "com.asiainfo.openboss." + key;
	}

	public ActionServlet() {
		super();
	}

	public void init() throws ServletException {
		super.init();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		service(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		service(request, response);
	}

	public void service(HttpServletRequest request, HttpServletResponse response) {

		String strPathInfo = request.getServletPath();// 形如/login/LoginAction_initBusi.action
		log.info("servlet路径:" + strPathInfo);
		String actionType = strPathInfo
				.substring(strPathInfo.lastIndexOf(".") + 1);
		log.info(actionType);

		String classname = null;// 类名
		String method = null;// 方法
		String returnType = "";// 返回类型,如:_h_upcmcc,表示:_是否包含头文件_使用的模板
		String busiType = null;// 业务类型，是ncs，还是cms等
		Object obj = null;// 对应action
		ActionInstance actionInstance = null;
		try {
			actionInstance = new ActionInstance(strPathInfo);
			classname = actionInstance.getActionPath();
			method = actionInstance.getMethodName();

			log.info("得到指定类"+classname);
			Class cls = Class.forName(classname);
			SpringBeanFactory.init("application.xml");
			
			
			
			String strMenuId = null;
			strMenuId = request.getParameter("menuId");// 菜单ID
			if (strMenuId == null || "".equals(strMenuId)) {// menuaction必须带有menuid
				String strErrMsg = "menuId不存在.";
				logger.error(strErrMsg);
				throw new ServletException(strErrMsg);
			}
			obj = MenuActionFactory.getMenuAction(strMenuId, cls);
//			} else {// action
//				obj = SpringBeanFactory.getBeanFactory().getBean(cls);
//			}

			log.info("得到指定方法"+method);
			Method mth = cls.getMethod(method,new Class[] { ReqData.class });
			
			log.info("得到方法入参,即request和response");
			ReqData rd = new ReqData();
			rd.setRequest(request);
			rd.setResponse(response);
			
			
			log.info("执行方法"+method+"，进入逻辑");
			Calendar beginCalendar = Calendar.getInstance();
			
			mth.invoke(obj, new Object[] { rd });
			
			Calendar endCalendar = Calendar.getInstance();
			long m = endCalendar.getTimeInMillis()- beginCalendar.getTimeInMillis();
			log.info(classname+"."+method+"业务耗时"+m+"毫秒");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// if (strPathInfo != null) {
		// strPathInfo = strPathInfo.substring(1, strPathInfo.lastIndexOf("."));
		// busiType = strPathInfo.substring(0, strPathInfo.indexOf("/"));
		// classname = getClassPrefix(busiType)
		// + "."
		// + strPathInfo.substring(strPathInfo.indexOf("/") + 1,
		// strPathInfo.lastIndexOf("/")).replaceAll("/",
		// ".");// 类名
		// method = strPathInfo.substring(strPathInfo.lastIndexOf("/") + 1,
		// strPathInfo.length());// 方法
		// if (method.indexOf("_") >= 0) {
		// returnType = method.substring(method.indexOf("_") + 1);
		// method = method.substring(0, method.indexOf("_"));
		// }
		// }

		// action示例：/ncs/demo/DemoAction/main.action
		// 映射到：com.asiainfo.openboss.ncs.demo.DemoAction.main();
		// 方法如带下划线，则表示声明了返回类型，示例：
		// /ncs/demo/DemoAction/main_h.action : 返回带有html头的完整页面
		// /ncs/demo/DemoAction/main.action : 返回不带html头的div片段
		// String classname = null;// 类名
		// String method = null;// 方法
		// String busiType = null;// 业务类型，是ncs，还是cms等
		// String returnType = "";// 返回类型,如:_h_upcmcc,表示:_是否包含头文件_使用的模板
		// String strPathInfo = request.getServletPath();// servlet路径
		// logger.debug("strPathInfo[" + strPathInfo + "]");
		// String actionType =
		// strPathInfo.substring(strPathInfo.lastIndexOf(".") + 1);
		//
		// if (strPathInfo != null) {
		// strPathInfo = strPathInfo.substring(1, strPathInfo.lastIndexOf("."));
		// busiType = strPathInfo.substring(0, strPathInfo.indexOf("/"));
		// classname = getClassPrefix(busiType)
		// + "."
		// + strPathInfo.substring(strPathInfo.indexOf("/") + 1,
		// strPathInfo.lastIndexOf("/")).replaceAll("/",
		// ".");// 类名
		// method = strPathInfo.substring(strPathInfo.lastIndexOf("/") + 1,
		// strPathInfo.length());// 方法
		// if (method.indexOf("_") >= 0) {
		// returnType = method.substring(method.indexOf("_") + 1);
		// method = method.substring(0, method.indexOf("_"));
		// }
		// }
		//
		// logger.debug("调用业务:类[" + classname + "],方法[" + method + "],类型[" +
		// busiType + "]");
		//
		// if (strPathInfo == null || strPathInfo.trim().equals("")) {
		// String strErrMsg = "地址输入错误.";
		// logger.error(strErrMsg);
		// throw new ServletException(strErrMsg);
		// }
		//
		// if (classname == null || classname.trim().equals("")) {
		// String strErrMsg = "页面不存在.";
		// logger.error(strErrMsg);
		// throw new ServletException(strErrMsg);
		// }
		//
		// if (busiType == null || busiType.trim().equals("")) {
		// String strErrMsg = "页面不存在.";
		// logger.error(strErrMsg);
		// throw new ServletException(strErrMsg);
		// }
		// Class clazz = Class.forName(classname);
		// // 从spring工厂生成实例,action是无状态的，所以一个实例即可
		// Object obj;
		// String strMenuId = null;
		// if ("menu".equals(actionType)) {// menu
		// strMenuId = request.getParameter("_menuId");// 菜单ID
		// if (strMenuId == null || "".equals(strMenuId)) {//
		// menuaction必须带有menuid
		// String strErrMsg = "menuId不存在.";
		// logger.error(strErrMsg);
		// throw new ServletException(strErrMsg);
		// }
		// obj = MenuActionFactory.getMenuAction(strMenuId, clazz);
		// } else {// action
		// obj = SpringBeanFactory.getBeanFactory().getBean(clazz);
		// }
		//
		// Method mth = clazz.getMethod(method, new Class[] {
		// HttpServletRequest.class, HttpServletResponse.class });
		// mth.invoke(obj, new Object[] { request, response });

	}
}
